<script setup lang="ts">
import { onMounted, ref } from 'vue';
import Taro, { useRouter } from '@tarojs/taro';
import type { CalendarCardDay, FormInstance } from '@nutui/nutui-taro';
import { Left, Right } from '@nutui/icons-vue-taro';
import { useDateFormat } from '@vueuse/core';
import { createBook, delBook, listCover, updateBook } from '@/service/api';
import type { Book, Cover } from '@/interface';
import { getRequestUrl, showErrorMsg } from '@/service/request/helpers';

const list = ref<Array<Cover>>([]);
const currentCover = ref<Cover>(list.value[0]);
const swiperRef = ref();
const handlePrev = () => {
  swiperRef.value?.prev();
};
const handleNext = () => {
  swiperRef.value?.next();
};

const onCoverChange = (index: number) => {
  currentCover.value = list.value[index];
};

const formRef = ref<FormInstance>();

const bookForm = ref<Book>({
  id: '',
  bookName: '',
  receiveDate: '',
  coverId: '',
  remark: ''
});

const calendarCardShow = ref(false);

// 默认为新增页面，有可能是编辑页面，需要显示删除和保存按钮
const settingPage = ref<boolean>(false);

const onDayClick = (day: CalendarCardDay) => {
  bookForm.value.receiveDate = `${day.year}-${day.month}-${day.date}`;
  calendarCardShow.value = false;
};

const selectedReceiveDate = ref<Date>(new Date());

const flushBookList = () => {
  const pages = Taro.getCurrentPages();
  const current = pages[pages.length - 1];
  current.getOpenerEventChannel().emit('flushData');
};

const onReceiveDateFocus = () => {
  if (!bookForm.value.receiveDate) return;
  selectedReceiveDate.value = new Date(bookForm.value.receiveDate);
};

onMounted(() => {
  const router = useRouter();
  const { tag } = router.params;
  if (tag) {
    settingPage.value = true;
  }
  const pages = Taro.getCurrentPages();
  const current = pages[pages.length - 1];
  current.getOpenerEventChannel().on('initData', (data: Book) => {
    bookForm.value.id = data.id;
    bookForm.value.userId = data.userId;
    bookForm.value.bookName = data.bookName;
    bookForm.value.familyId = data.familyId;
    bookForm.value.receiveDate = useDateFormat(data.receiveDate, 'YYYY-MM-DD').value;
    bookForm.value.remark = data.remark;
    bookForm.value.coverPath = data.coverPath;
  });
  listCover().then((res: Service.SuccessResult) => {
    if (res.success.length) {
      res.success.forEach((item: Cover) => list.value.push(item));
      currentCover.value = list.value[0];
    }
  });
});

const onSave = () => {
  formRef.value?.validate().then(res => {
    const { valid, errors } = res as { valid: boolean; errors: Array<object> };
    if (valid) {
      Taro.showLoading({ title: '保存中...' });
      bookForm.value.coverId = currentCover.value.id;
      if (bookForm.value.id) {
        console.log(bookForm.value);
        updateBook(bookForm.value)
          .then(() => {
            Taro.hideLoading();
            Taro.navigateBack({
              delta: 1
            });
            flushBookList();
          })
          .catch((err: Service.RequestError) => {
            Taro.hideLoading();
            showErrorMsg(err.message);
          });
      } else {
        createBook(bookForm.value)
          .then(() => {
            Taro.hideLoading();
            Taro.navigateBack({
              delta: 1
            });
            flushBookList();
          })
          .catch((err: Service.RequestError) => {
            Taro.hideLoading();
            showErrorMsg(err.message);
          });
      }
    } else {
      console.log(errors[0]);
      showErrorMsg(`${errors[0]}`);
    }
  });
};

const showDeleteDialog = ref<boolean>(false);
const onDelete = () => {
  showDeleteDialog.value = true;
};
const onDelConfirm = () => {
  if (bookForm.value.id) {
    Taro.showLoading({ title: '删除中...' });
    delBook(bookForm.value.id)
      .then(() => {
        Taro.hideLoading();
        Taro.navigateBack({
          delta: 1
        });
        flushBookList();
      })
      .catch((err: Service.RequestError) => {
        Taro.hideLoading();
        showErrorMsg(err.message);
      });
  }
};

const onCancel = () => {
  showDeleteDialog.value = false;
};
</script>

<template>
  <basic-layout :show-tab-bar="false">
    <custom-nav-bar left-show title="创建礼簿" />
    <div class="w-375px text-30px">
      <div class="w-100% h-100px flex justify-center items-center mt-12px ma relative">
        <nut-swiper
          ref="swiperRef"
          :init-page="0"
          pagination-color="#F44336"
          auto-play="0"
          :loop="false"
          :height="90"
          :width="135"
          style="width: 135px; height: 90px; border-radius: 5px"
          @change="onCoverChange"
        >
          <nut-swiper-item v-for="(item, index) in list" :key="index">
            <image
              class="w-135px h-90px b-rd-5px shadow"
              :src="getRequestUrl('/admin' + item.coverPath)"
              :alt="item.coverName"
            />
          </nut-swiper-item>
        </nut-swiper>
        <div class="swiper-btns">
          <div class="swiper-btn" @click="handlePrev">
            <Left></Left>
          </div>
          <div class="swiper-btn" @click="handleNext">
            <Right></Right>
          </div>
        </div>
      </div>
      <div class="w-46% h-40px mt-10px ma text-#9ca3af text-12px flex justify-center items-center b-rd-8px">
        左右切换选择礼簿封面
      </div>
      <nut-form ref="formRef" star-position="right" :model-value="bookForm" label-position="top">
        <nut-form-item
          label="礼簿名称"
          prop="bookName"
          required
          :rules="[{ required: true, message: '请填写礼簿名称' }]"
        >
          <nut-input v-model="bookForm.bookName" placeholder="" type="text" :border="false" />
        </nut-form-item>
        <nut-form-item
          label="收礼日期"
          prop="receiveDate"
          required
          :rules="[{ required: true, message: '请选择收礼日期' }]"
        >
          <nut-input
            v-model="bookForm.receiveDate"
            placeholder=""
            type="text"
            readonly
            :border="false"
            @click="calendarCardShow = true"
            @focus="onReceiveDateFocus"
          />
          <nut-popup
            :visible="calendarCardShow"
            position="bottom"
            safe-area-inset-bottom
            @click-overlay="calendarCardShow = false"
          >
            <nut-calendar-card v-model="selectedReceiveDate" type="single" @day-click="onDayClick"></nut-calendar-card>
          </nut-popup>
        </nut-form-item>
        <nut-form-item label="备注信息">
          <textarea
            v-model="bookForm.remark"
            placeholder=" "
            class="bg-#f7f8fa h-100px w-100% b-rd-5px right-4px left-1px"
          />
        </nut-form-item>
      </nut-form>
      <nut-space direction="vertical" fill>
        <nut-button plain class="hoo-btn hoo-btn--confirm" block @click="onSave">保存</nut-button>
        <nut-button v-show="settingPage" plain class="hoo-btn hoo-btn--delete" block @click="onDelete">删除</nut-button>
      </nut-space>
      <nut-dialog
        v-model:visible="showDeleteDialog"
        title="警告"
        content="数据删除后不能回复，确认是否删除?"
        @cancel="onCancel"
        @ok="onDelConfirm"
      />
    </div>
  </basic-layout>
</template>

<style lang="scss">
@import '@/styles/custom';
</style>
